package com.linkoog.devtools.type_index;

import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.PsiManager;
import com.intellij.util.indexing.DataIndexer;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexExtension;
import com.intellij.util.indexing.FileContent;
import com.intellij.util.indexing.ID;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.EnumeratorStringDescriptor;
import com.intellij.util.io.KeyDescriptor;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassFieldIndex extends FileBasedIndexExtension<String, List<String>> {

    public static final ID<String, List<String>> INDEX_ID = ID.create("ClassFieldIndex");

    @Override
    public @NotNull ID<String, List<String>> getName() {
        return INDEX_ID;
    }

    @Override
    public @NotNull DataIndexer<String, List<String>, FileContent> getIndexer() {
        return inputData -> {
            Map<String, List<String>> map = new HashMap<>();
            PsiFile psiFile = PsiManager.getInstance(inputData.getProject()).findFile(inputData.getFile());
            if (psiFile instanceof PsiJavaFile) {
                for (PsiClass psiClass : ((PsiJavaFile) psiFile).getClasses()) {
                    String className = psiClass.getQualifiedName();
                    if (className != null) {
                        List<String> fieldInfoList = new ArrayList<>();
                        for (PsiField field : psiClass.getFields()) {
                            // 收集字段名和类型
                            String fieldInfo = field.getName() + ":" + field.getType().getCanonicalText();
                            fieldInfoList.add(fieldInfo);
                        }
                        map.put(className, fieldInfoList);
                    }
                }
            }
            return map;
        };
    }

    @Override
    public @NotNull KeyDescriptor<String> getKeyDescriptor() {
        return new EnumeratorStringDescriptor();
    }

    @Override
    public @NotNull DataExternalizer<List<String>> getValueExternalizer() {
        return new ListExternalizer();
    }

    @Override
    public int getVersion() {
        return 1;
    }

    @Override
    public @NotNull FileBasedIndex.InputFilter getInputFilter() {
        return file -> file.getFileType() == JavaFileType.INSTANCE;
    }

    @Override
    public boolean dependsOnFileContent() {
        return true;
    }
}

